<template>
  <view class="points-mall-container">
    <!-- 顶部积分信息 -->
    <view class="points-header">
      <view class="points-balance">
        <text class="label">我的积分</text>
        <text class="value">{{ userPoints }}<text class="unit">分</text></text>
      </view>
      <view class="points-actions">
        <view class="action-item" @click="viewPointsDetail">
          <text>积分明细</text>
          <uni-icons type="arrowright" size="16" color="#fff"></uni-icons>
        </view>
        <view class="action-item" @click="viewPointsRule">
          <text>积分规则</text>
          <uni-icons type="arrowright" size="16" color="#fff"></uni-icons>
        </view>
      </view>
    </view>
    
    <!-- 积分分类 -->
    <scroll-view class="category-scroll" scroll-x>
      <view 
        class="category-item" 
        v-for="category in categories" 
        :key="category.id"
        :class="{active: activeCategoryId === category.id}"
        @click="changeCategory(category.id)"
      >
        <text>{{ category.name }}</text>
      </view>
    </scroll-view>
    
    <!-- 积分商品列表 -->
    <scroll-view 
      class="product-scroll" 
      scroll-y
      @scrolltolower="loadMore"
    >
      <!-- 推荐商品 -->
      <view class="recommend-section" v-if="activeCategoryId === 'recommend'">
        <view class="section-title">
          <text>热门兑换</text>
        </view>
        <view class="recommend-list">
          <view 
            class="recommend-item" 
            v-for="product in recommendProducts" 
            :key="product.id"
            @click="viewProductDetail(product.id)"
          >
            <image class="product-image" :src="product.image" mode="aspectFill"></image>
            <view class="product-info">
              <text class="product-name">{{ product.name }}</text>
              <view class="product-points">
                <text class="points-value">{{ product.points }}</text>
                <text class="points-unit">积分</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 普通商品列表 -->
      <view class="product-list">
        <view 
          class="product-item" 
          v-for="product in productList" 
          :key="product.id"
          @click="viewProductDetail(product.id)"
        >
          <image class="product-image" :src="product.image" mode="aspectFill"></image>
          <view class="product-info">
            <text class="product-name">{{ product.name }}</text>
            <view class="product-meta">
              <text class="sales">已兑{{ product.sales }}件</text>
              <text class="stock" v-if="product.stock > 0">剩余{{ product.stock }}件</text>
              <text class="stock empty" v-else>已兑完</text>
            </view>
            <view class="product-footer">
              <view class="points-info">
                <text class="points-value">{{ product.points }}</text>
                <text class="points-unit">积分</text>
              </view>
              <button 
                class="exchange-btn" 
                :class="{disabled: product.stock <= 0}"
                :disabled="product.stock <= 0"
                @click.stop="exchangeProduct(product)"
              >
                {{ product.stock > 0 ? '立即兑换' : '已售罄' }}
              </button>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载状态 -->
      <view class="load-status">
        <uni-load-more 
          :status="loadStatus" 
          :content-text="{
            contentdown: '上拉加载更多',
            contentrefresh: '加载中',
            contentnomore: '没有更多了'
          }" 
        />
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="productList.length === 0 && !loading">
        <image 
          class="empty-image" 
          src="/static/images/empty-points.png" 
          mode="aspectFit"
        ></image>
        <text class="empty-text">暂无商品</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 用户积分
const userPoints = ref(3560)

// 分类数据
const categories = ref([
  { id: 'recommend', name: '推荐' },
  { id: 'digital', name: '数码家电' },
  { id: 'daily', name: '生活日用' },
  { id: 'food', name: '食品饮料' },
  { id: 'coupon', name: '优惠券' },
  { id: 'vip', name: '会员权益' }
])
const activeCategoryId = ref('recommend')

// 推荐商品
const recommendProducts = ref([
  {
    id: '1',
    name: '50元京东E卡',
    points: 5000,
    image: '/static/images/product-jd-card.jpg',
    sales: 125
  },
  {
    id: '2',
    name: '腾讯视频月卡',
    points: 3000,
    image: '/static/images/product-tx-vip.jpg',
    sales: 89
  },
  {
    id: '3',
    name: '星巴克中杯券',
    points: 2500,
    image: '/static/images/product-starbucks.jpg',
    sales: 156
  }
])

// 商品列表
const productList = ref([])
const page = ref(1)
const pageSize = 10
const loadStatus = ref('more') // more / loading / noMore
const loading = ref(false)

// 页面加载
onLoad(() => {
  // 获取初始数据
  fetchUserPoints()
  fetchProducts()
})

// 获取用户积分
const fetchUserPoints = () => {
  // 模拟API请求
  console.log('获取用户积分')
}

// 获取商品数据
const fetchProducts = () => {
  if (loadStatus.value === 'noMore') return
  
  loadStatus.value = 'loading'
  loading.value = true
  
  // 模拟API请求延迟
  setTimeout(() => {
    // 模拟数据
    const newData = generateMockProducts(page.value, pageSize, activeCategoryId.value)
    
    if (newData.length === 0) {
      loadStatus.value = 'noMore'
      if (page.value === 1) {
        productList.value = []
      }
    } else {
      productList.value = page.value === 1 ? newData : [...productList.value, ...newData]
      page.value++
      loadStatus.value = newData.length < pageSize ? 'noMore' : 'more'
    }
    
    loading.value = false
  }, 800)
}

// 生成模拟商品数据
const generateMockProducts = (page, size, categoryId) => {
  if (page > 3) return [] // 模拟只有3页数据
  
  const categoryNames = {
    'digital': '数码家电',
    'daily': '生活日用',
    'food': '食品饮料',
    'coupon': '优惠券',
    'vip': '会员权益'
  }
  
  const data = []
  for (let i = 0; i < size; i++) {
    const points = [500, 1000, 1500, 2000, 2500, 3000, 5000][Math.floor(Math.random() * 7)]
    const stock = Math.floor(Math.random() * 100)
    
    data.push({
      id: `product_${categoryId}_${page}_${i}`,
      name: `${categoryNames[categoryId] || ''}商品${page}_${i}`,
      points,
      image: `/static/images/product-${Math.floor(Math.random() * 5) + 1}.jpg`,
      sales: Math.floor(Math.random() * 100),
      stock,
      category: categoryId
    })
  }
  
  return data
}

// 切换分类
const changeCategory = (categoryId) => {
  activeCategoryId.value = categoryId
  // 重置分页数据
  page.value = 1
  productList.value = []
  loadStatus.value = 'more'
  // 重新加载数据
  fetchProducts()
}

// 加载更多
const loadMore = () => {
  fetchProducts()
}

// 查看商品详情
const viewProductDetail = (productId) => {
  uni.navigateTo({
    url: `/pages/points/detail?id=${productId}`
  })
}

// 兑换商品
const exchangeProduct = (product) => {
  if (product.points > userPoints.value) {
    uni.showModal({
      title: '积分不足',
      content: `您的积分不足，还需${product.points - userPoints.value}积分才能兑换该商品`,
      confirmText: '赚取积分',
      success: (res) => {
        if (res.confirm) {
          viewPointsRule()
        }
      }
    })
    return
  }
  
  uni.navigateTo({
    url: `/pages/points/exchange?id=${product.id}`
  })
}

// 查看积分明细
const viewPointsDetail = () => {
  uni.navigateTo({
    url: '/pages/points/index'
  })
}

// 查看积分规则
const viewPointsRule = () => {
  uni.navigateTo({
    url: '/pages/points/rules'
  })
}
</script>

<style lang="scss" scoped>
.points-mall-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: $light-bg;
  overflow-x: hidden;
}

.points-header {
  padding: 40rpx 30rpx;
  background: linear-gradient(135deg, $primary-color, $secondary-color);
  color: $text-color-inverse;
  
  .points-balance {
    margin-bottom: 40rpx;
    
    .label {
      font-size: $font-size-28rpx;
      opacity: 0.9;
      display: block;
      margin-bottom: 10rpx;
    }
    
    .value {
      font-size: 60rpx;
      font-weight: bold;
      
      .unit {
        font-size: $font-size-28rpx;
        margin-left: 10rpx;
      }
    }
  }
  
  .points-actions {
    display: flex;
    
    .action-item {
      display: flex;
      align-items: center;
      margin-right: 40rpx;
      font-size: $font-size-26rpx;
      opacity: 0.9;
      
      text {
        margin-right: 8rpx;
      }
    }
  }
}

.category-scroll {
  white-space: nowrap;
  padding: 20rpx 30rpx;
  background-color: $white-bg;
  border-bottom: 1rpx solid #f5f5f5;
  
  .category-item {
    display: inline-block;
    padding: 10rpx 30rpx;
    margin-right: 20rpx;
    font-size: $font-size-28rpx;
    color: $text-color;
    background-color: $light-bg;
    border-radius: 30rpx;
    
    &.active {
      color: $text-color-inverse;
      background-color: $primary-color;
    }
  }
}

.product-scroll {
  flex: 1;
  height: calc(100vh - 340rpx);
}

.recommend-section {
  padding: 30rpx;
  background-color: $white-bg;
  margin-bottom: 20rpx;
  
  .section-title {
    font-size: $font-size-30rpx;
    font-weight: bold;
    color: $text-color;
    margin-bottom: 30rpx;
  }
  
  .recommend-list {
    display: flex;
    overflow-x: auto;
    padding-bottom: 20rpx;
    
    .recommend-item {
      width: 300rpx;
      margin-right: 20rpx;
      flex-shrink: 0;
      background-color: $white-bg;
      border-radius: 12rpx;
      overflow: hidden;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
      
      .product-image {
        width: 100%;
        height: 300rpx;
      }
      
      .product-info {
        padding: 20rpx;
        
        .product-name {
          font-size: $font-size-28rpx;
          color: $text-color;
          @include text-ellipsis(2);
          line-height: 1.4;
          margin-bottom: 20rpx;
        }
        
        .product-points {
          .points-value {
            font-size: $font-size-32rpx;
            color: $primary-color;
            font-weight: bold;
          }
          
          .points-unit {
            font-size: $font-size-24rpx;
            color: $primary-color;
            margin-left: 6rpx;
          }
        }
      }
    }
  }
}

.product-list {
  padding: 20rpx;
  
  .product-item {
    display: flex;
    margin-bottom: 30rpx;
    background-color: $white-bg;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
    
    .product-image {
      width: 220rpx;
      height: 220rpx;
      flex-shrink: 0;
    }
    
    .product-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 20rpx;
      min-width: 0;
      
      .product-name {
        font-size: $font-size-28rpx;
        color: $text-color;
        @include text-ellipsis(2);
        line-height: 1.4;
        margin-bottom: 15rpx;
      }
      
      .product-meta {
        display: flex;
        margin-bottom: 20rpx;
        font-size: $font-size-24rpx;
        color: $text-color-666;
        
        .sales {
          margin-right: 20rpx;
        }
        
        .stock {
          &.empty {
            color: #F44336;
          }
        }
      }
      
      .product-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: auto;
        
        .points-info {
          .points-value {
            font-size: $font-size-32rpx;
            color: $primary-color;
            font-weight: bold;
          }
          
          .points-unit {
            font-size: $font-size-24rpx;
            color: $primary-color;
            margin-left: 6rpx;
          }
        }
        
        .exchange-btn {
          height: 60rpx;
          line-height: 60rpx;
          padding: 0 30rpx;
          font-size: $font-size-26rpx;
          color: $text-color-inverse;
          background-color: $primary-color;
          border-radius: 30rpx;
          
          &.disabled {
            background-color: #ccc;
          }
        }
      }
    }
  }
}

.load-status {
  padding: 30rpx 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0;
  
  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
    opacity: 0.6;
  }
  
  .empty-text {
    font-size: $font-size-28rpx;
    color: $text-color-666;
  }
}
</style>